package com.example.oppotest.util.youku;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @Author wyk
 * @Date: 2025/2/25 22:12
 * MD5值获取工具
 */
public class Md5Util {

    /**
     * 获取String字符串的MD5
     *
     * @param s
     * @return
     */
    public static String MD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes(StandardCharsets.UTF_8));
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    /**
     * 将 OAID 转换为 32 位设备号（MD5）
     *
     * @param oaid 平台传入的 OAID
     * @return 32 位设备号
     * @throws NoSuchAlgorithmException 如果 MD5 算法不可用
     */
    public static String generate32BitDeviceId(String oaid) throws NoSuchAlgorithmException {
        // 创建 MD5 哈希算法实例
        MessageDigest md = MessageDigest.getInstance("MD5");

        // 计算哈希值
        byte[] hashBytes = md.digest(oaid.getBytes());

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }

    /**
     * 将字节数组转换为 UUID
     *
     * @param hashBytes 哈希值字节数组
     * @return UUID
     */
    public static UUID bytesToUuid(byte[] hashBytes) {
        long mostSigBits = 0;
        long leastSigBits = 0;

        // 取前 16 个字节生成 UUID
        for (int i = 0; i < 8; i++) {
            mostSigBits = (mostSigBits << 8) | (hashBytes[i] & 0xff);
        }
        for (int i = 8; i < 16; i++) {
            leastSigBits = (leastSigBits << 8) | (hashBytes[i] & 0xff);
        }

        return new UUID(mostSigBits, leastSigBits);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String oaid = "b50b3cb94e1e946b93991265580e79544225d5b2fbf838fcb92a2b991969a685";
        // 使用 SHA-256 哈希算法
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = md.digest(oaid.getBytes());
        System.out.println(bytesToUuid(hashBytes));
        System.out.println(MD5(oaid));
        System.out.println(generate32BitDeviceId(oaid));
    }

}
